package Day08.RPCDemo02.src.cn.tedu.utils;

import java.io.*;

/**
 * 序列化工具类
 */
public class SeriUtils {
    private SeriUtils() {
    }

    /**
     * 对象转字节
     */
    public static byte[] obj2Bytes(Object obj) {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream out = null;
        try {
            bos = new ByteArrayOutputStream();
            out = new ObjectOutputStream(bos);
            out.writeObject(obj);
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关闭流
            try {
                if (bos != null) {
                    bos.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 字节转对象
     */
    public static Object bytes2Obj(byte[] bytes)  {
        ByteArrayInputStream bin = null;
        ObjectInputStream in = null;
        try {
            bin = new ByteArrayInputStream(bytes);
            in = new ObjectInputStream(bin);
            Object obj = in.readObject();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            //关闭流
            try {
                if (bin != null) {
                    bin.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

}
